package com.ojoin.trade.supplyloan_core.web.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ojoin.trade.supplyloan_core.web.domain.*;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ojoin.trade.common.Constants;
import com.ojoin.trade.common.constdef.IConstDef;
import com.ojoin.trade.common.exception.BusinessException;
import com.ojoin.trade.common.exception.IPayNowException;
import com.ojoin.trade.common.utils.CommonUtils;
import com.ojoin.trade.common.utils.DownloadUtils;
import com.ojoin.trade.common.utils.FileUploadUtils;
import com.ojoin.trade.common.utils.LogUtils;
import com.ojoin.trade.common.utils.TimeUtils;
import com.ojoin.trade.common.web.controller.SimpleBaseController;
import com.ojoin.trade.common.web.domain.Result;
import com.ojoin.trade.common.web.domain.TbUploadFile;
import com.ojoin.trade.common.web.service.IRSAService;
import com.ojoin.trade.common.web.service.TbUploadFileService;
import com.ojoin.trade.common_core.utils.TradeUtils;
import com.ojoin.trade.common_core.web.domain.TbMerchantUser;
import com.ojoin.trade.common_core.web.domain.TbMerchantuserFinaccount;
import com.ojoin.trade.common_core.web.service.MerchantUserBaseService;
import com.ojoin.trade.common_core.web.service.TbMerchantuserFinaccountService;
import com.ojoin.trade.supplyloan_core.constdef.ISLConstDef;
import com.ojoin.trade.supplyloan_core.web.service.TbRedoService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlLoanCaculateFeeService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlLoanCreditService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlLoanInfoService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlLoanRefundService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlLoanService;
import com.ojoin.trade.t0loan_core.web.domain.TbT0RefundTaskVO;
import com.ojoin.trade.t0loan_core.web.service.T0LoanBaseService;
import com.ojoin.trade.t0loan_core.web.service.T0LoanTransanctionLogBaseService;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 15-11-11
 * Time: 上午11:42
 * To change this template use File | Settings | File Templates.
 */
 @Controller
 @RequestMapping("/operate")
 public class OperatorSlLoanController  extends SimpleBaseController {

   private Logger log= LoggerFactory.getLogger(OperatorSlLoanController.class);
   
   @Autowired
   private TbSlLoanCreditService tbSlLoanCreditService;

    @Autowired
    private MerchantUserBaseService userBaseService;



    @Autowired
    TbSlLoanCaculateFeeService tbSlLoanCaculateFeeService;

    @Autowired
    private IRSAService rsaSrv;


    @Autowired
    private TbSlLoanService loanService;

    @Autowired
    private T0LoanBaseService t0loanService;
    
    @Autowired
    private T0LoanTransanctionLogBaseService translogService;
    
    @Autowired
    private TbSlLoanRefundService tbSlLoanRefundService;

    @Autowired
    private TbSlLoanInfoService tbSlLoanInfoService;
    @Autowired
    private TbUploadFileService uploadFileService;

    @Autowired
    private TbMerchantuserFinaccountService tbMerchantuserFinaccountService;

    @Autowired
    private TbRedoService tbRedoService;
   //查询待办的贷款任务
    @ResponseBody
    @RequestMapping(value = "/slqueryloantask", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public Result slqueryLoanTask(HttpServletRequest request,Pageable page){

     try{
         List<SlLoanTodoTaskVO>  list=tbSlLoanCreditService.queryToDoTask(page);
         return new Result(Result.Status.OK,list);
     }catch(Exception e){
         log.error("查询商户的贷款的未待办任务出错,请重试",e);
         if(e instanceof BusinessException){
             return new Result(Result.Status.ERROR,e.getMessage());
         }
         return new Result(Result.Status.ERROR,"查询商户的贷款的未待办任务出错,请重试");
     }
    }
    @ResponseBody
    @RequestMapping(value = "/slqueryfirsttrialloan", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
   public Result slqueryfirsttrialloan(HttpServletRequest request,Pageable page){
        	Integer  userIdOfJoinOfCreditor=TradeUtils.getOperatorCompany(request);
            try{
                List<TbSlStatusCreditLogVo>  list =tbSlLoanCreditService.queryCreditLogByStatus(IConstDef.OPERATOR_POWERTYPE_PREAPPROVE,userIdOfJoinOfCreditor,page);
                return new Result(Result.Status.OK,list);
               }catch(BusinessException e){
                log.error("查询需要初审的贷款数据出错",e);
                if(e instanceof  BusinessException){
                    return new Result(Result.Status.ERROR,e.getMessage());
                }
                return new Result(Result.Status.ERROR,"查询需要初审的贷款数据出错");

            }
    }
    @ResponseBody
    @RequestMapping(value = "/slqueryrealloan", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public Result slQueryRealLoan(HttpServletRequest request,Pageable page){
    	Integer  userIdOfJoinOfCreditor=TradeUtils.getOperatorCompany(request);
        
        try{
            List<TbSlStatusCreditLogVo>  list =tbSlLoanCreditService.queryCreditLogByStatus(IConstDef.OPERATOR_POWERTYPE_CREDIT,userIdOfJoinOfCreditor,page);
            return new Result(Result.Status.OK,list);
        }catch(BusinessException e){
            log.error("查询需要放款的贷款数据出错",e);
            if(e instanceof  BusinessException){
                return new Result(Result.Status.ERROR,e.getMessage());
            }
            return new Result(Result.Status.ERROR,"查询需要放款的贷款数据出错");

        }
    }
    @ResponseBody
    @RequestMapping(value="/slquerybycause",method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE)
    public Result slQueryByCause(HttpServletRequest request, String mhtname,String code,Pageable page){
    	Integer  userIdOfJoinOfCreditor=TradeUtils.getOperatorCompany(request);
        Map<String,Object> map=new HashMap<String,Object>();
        if(!CommonUtils.isEmpty(mhtname)){
               map.put("mhtname",mhtname);
        }
        if(!CommonUtils.isEmpty(code)){
            map.put("code",code);
        }
        map.put("userIdOfJoinOfCreditor",userIdOfJoinOfCreditor);

        try{
            List<TbSlLoanCreditLogVo>  list =tbSlLoanCreditService.queryPayBackCreditLogByCause(map,page);
            return new Result(Result.Status.OK,list);
        }catch(BusinessException e){
            log.error("查询需要放款的贷款数据出错",e);
            if(e instanceof  BusinessException){
                return new Result(Result.Status.ERROR,e.getMessage());
            }
            return new Result(Result.Status.ERROR,"查询需要放款的贷款数据出错");

        }

    }
    @ResponseBody
    @RequestMapping(value = "/slrefuseloan", method=RequestMethod.POST)
    public  Result slrefuseloan(HttpServletRequest request,String id,String memo,String rowUpdateTime){
    	int idOfTbFactoryingCompany=TradeUtils.getOperatorCompany(request);
        if(StringUtils.isEmpty(id)){
            return new Result(Result.Status.ERROR,"未选择任何需要拒绝的贷款数据");
        }

        try{
            memo= URLDecoder.decode(memo,Constants.ENCODING);
        }catch(Exception e){

        }
        if(StringUtils.isEmpty(memo)){
           return new Result(Result.Status.ERROR,"拒绝理由不能为空");
       }
        try{
            loanService.updateForRefuseLoan(Integer.parseInt(id), idOfTbFactoryingCompany, memo, rowUpdateTime);
        return new Result(Result.Status.OK,"拒绝放款成功");
        }catch (Exception e){
            if(e instanceof BusinessException){
               return new Result(Result.Status.ERROR,e.getMessage());
            }
            return new Result(Result.Status.ERROR,"拒绝放款有误");
        }


    }
    @ResponseBody
    @RequestMapping(value = "/downloadSlLoanMaterial", method = RequestMethod.GET)
    public void downloadSlLoanMaterial(
            HttpServletRequest request,
            HttpServletResponse response,int id) {

        TbSlLoanCreditLog creditlog= tbSlLoanCreditService.queryCreditLogById(id);
        if(!CommonUtils.isEmpty(creditlog.getMaterial())){
            TbUploadFile uploadFileVO = uploadFileService.queryById(CommonUtils.getInt(creditlog.getMaterial()));
            String filename = "贷款编号"+creditlog.getCode()+IConstDef.DOWNLOAD_LOANAPPLY + "." + FilenameUtils.getExtension(uploadFileVO.getDownloadPath());
            try {
                DownloadUtils.download(request, response, FileUploadUtils.getDefaultBaseDir()+File.separator+uploadFileVO.getDownloadPath(), filename);
            }catch (Exception e) {
                LogUtils.info(log, "下载%s",IConstDef.DOWNLOAD_LOANAPPLY);
            }
        }
    }
    @ResponseBody
         @RequestMapping(value = "/downloadSlLoanContract", method = RequestMethod.GET)
         public void downloadSlLoanContract(
            HttpServletRequest request,
            HttpServletResponse response,int id) {

        TbSlLoanCreditLog creditlog= tbSlLoanCreditService.queryCreditLogById(id);
        if(!CommonUtils.isEmpty(creditlog.getMaterial())){
            TbUploadFile uploadFileVO = uploadFileService.queryById(CommonUtils.getInt(creditlog.getContract()));
            String filename = "贷款编号"+creditlog.getCode()+IConstDef.DOWNLOAD_CONTRACT + "." + FilenameUtils.getExtension(uploadFileVO.getDownloadPath());
            try {
                DownloadUtils.download(request, response, FileUploadUtils.getDefaultBaseDir()+File.separator+uploadFileVO.getDownloadPath(), filename);
            }catch (Exception e) {
                LogUtils.info(log, "下载%s",IConstDef.DOWNLOAD_CONTRACT);
            }
        }
    }
    @ResponseBody
    @RequestMapping(value = "/downloadSlLoanRegister", method = RequestMethod.GET)
    public void downloadSlLoanRegister(
            HttpServletRequest request,
            HttpServletResponse response,int id) {

        TbSlLoanCreditLog creditlog= tbSlLoanCreditService.queryCreditLogById(id);
        if(!CommonUtils.isEmpty(creditlog.getLoanregist())){
            TbUploadFile uploadFileVO = uploadFileService.queryById(CommonUtils.getInt(creditlog.getLoanregist()));
            String filename = "贷款编号"+creditlog.getCode()+IConstDef.DOWNLOAD_LOANREGIST + "." + FilenameUtils.getExtension(uploadFileVO.getDownloadPath());
            try {
                DownloadUtils.download(request, response, FileUploadUtils.getDefaultBaseDir()+File.separator+uploadFileVO.getDownloadPath(), filename);
            }catch (Exception e) {
                LogUtils.info(log, "下载%s",IConstDef.DOWNLOAD_LOANREGIST);
            }
        }
    }

    @ResponseBody
    @RequestMapping(value = "/downloadSlLoanVouncher", method = RequestMethod.GET)
    public void downloadSlLoanVouncher(
            HttpServletRequest request,
            HttpServletResponse response,int id) {
        TbSlLoanCreditLog creditlog= tbSlLoanCreditService.queryCreditLogById(id);
        if(!CommonUtils.isEmpty(creditlog.getLoanVoucher())){
        TbUploadFile uploadFileVO = uploadFileService.queryById(CommonUtils.getInt(creditlog.getLoanVoucher()));
        String filename = "贷款编号"+creditlog.getCode()+IConstDef.DOWNLOAD_LOANVOUCHER + "." + FilenameUtils.getExtension(uploadFileVO.getDownloadPath());
        try {
        DownloadUtils.download(request, response, FileUploadUtils.getDefaultBaseDir()+File.separator+uploadFileVO.getDownloadPath(), filename);
        }catch (Exception e) {
        LogUtils.info(log, "下载%s",IConstDef.DOWNLOAD_SLCREDITINFOFILE);
        }
        }
    }
    @ResponseBody
    @RequestMapping(value="/slqueryloan",method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE)
    public Result slqueryloan(HttpServletRequest request, Pageable page){
        Integer  userIdOfJoinOfCreditor=TradeUtils.getOperatorCompany(request);
         
        try{
            List<TbSlStatusCreditLogVo>  list =tbSlLoanCreditService.queryCreditLogByStatus(IConstDef.OPERATOR_POWERTYPE_CREDIT,userIdOfJoinOfCreditor,page);
            return new Result(Result.Status.OK,list);
        }catch (BusinessException e){
            log.error("查询需要放款的数据出错");
            if(e instanceof BusinessException){
                return new Result(Result.Status.ERROR,e.getMessage());
            }
            return new Result(Result.Status.ERROR,"查询需要放款的数据出错");
        }
    }
    @ResponseBody
    @RequestMapping(value="/downloanPaymentNotice",method =RequestMethod.GET )
    public void downloanPaymentNotice(
            HttpServletRequest request,
            HttpServletResponse response,int id) {
        TbSlLoanCreditLog creditlog= tbSlLoanCreditService.queryCreditLogById(id);
        if(!CommonUtils.isEmpty(creditlog.getPaymentNotice())){
            TbUploadFile uploadFileVO = uploadFileService.queryById(CommonUtils.getInt(creditlog.getPaymentNotice()));
            String filename = "贷款编号"+creditlog.getCode()+IConstDef.DOWNLOAD_PAYMENTORDER + "." + FilenameUtils.getExtension(uploadFileVO.getDownloadPath());
            try {
                DownloadUtils.download(request, response, FileUploadUtils.getDefaultBaseDir()+File.separator+uploadFileVO.getDownloadPath(), filename);
            }catch (Exception e) {
                LogUtils.info(log, "下载%s",IConstDef.DOWNLOAD_PAYMENTORDER);
            }
        }
    }
    @ResponseBody
    @RequestMapping(value = "/slfirsttrial",method = RequestMethod.POST)
    public Result  slfirsttrial(HttpServletRequest request,String id,String joinuserid,String rowUpdateTime,String loan_voucher,String paymentNotice,String contract,String loanregist ){
    	int idOfTbFactoryingCompany=TradeUtils.getOperatorCompany(request);
        if(StringUtils.isEmpty(id)){
            return new Result(Result.Status.ERROR,"未选择任何需要初审的贷款数据");
        }
        if(StringUtils.isEmpty(rowUpdateTime)){
            return  new Result(Result.Status.ERROR,"贷款的时间戳不可为空");
        }

        if(StringUtils.isEmpty(loan_voucher)){
            return new Result(Result.Status.ERROR,"凭证不能为空");
        }
//        if(StringUtils.isEmpty(paymentNotice)){
//            return new Result(Result.Status.ERROR,"付款通知书不能为空");
//        } ;
        if(StringUtils.isEmpty(contract)){
            return new Result(Result.Status.ERROR,"合同详情不能为空");
        }
        if(StringUtils.isEmpty(loanregist)){
            return new Result(Result.Status.ERROR,"不动资产登记不能为空");
        }

        if(StringUtils.isEmpty(joinuserid)){
            return new Result(Result.Status.ERROR,"joinid不能为空");
        }
        int join=Integer.parseInt(joinuserid);
          try{
              loanService.updateForfirsttrialSuccess(Integer.parseInt(id), idOfTbFactoryingCompany, rowUpdateTime,loan_voucher,paymentNotice,join,contract,loanregist);
              return new Result(Result.Status.OK,"初审成功");
          }catch (Exception e){
              log.error("贷款初审失败",e);
              if(e instanceof BusinessException){
               return new Result(Result.Status.ERROR,e.getMessage());
              }
              return new Result(Result.Status.ERROR,"初审失败");
          }
    }
    @ResponseBody
    @RequestMapping(value = "/slloan",method = RequestMethod.POST)
    public Result slloan(HttpServletRequest request,String id,String  rowUpdateTime,String pwd,String idofLoanInfo,String tsOfLoanInfo,String voucher){
      if(StringUtils.isEmpty(id)){
          return new Result(Result.Status.ERROR,"未选择任何的贷款记录");
      }
      if(StringUtils.isEmpty(rowUpdateTime)){
          return new Result(Result.Status.ERROR,"上一次变更的时间为空");
      }
      if(CommonUtils.isEmpty(voucher)&&StringUtils.isEmpty(pwd)){
          return  new Result(Result.Status.ERROR,"支付密码不能为空");
      }
      
       Integer idOfTbFactoryingOperator=CommonUtils.getLoginUserId();
       String mhtnofrom=TradeUtils.getOperatorCompanyMhtNo();
      
       pwd=rsaSrv.decryptStringByJs(pwd);
     
     try{
         loanService.updateForRealLoan(Integer.parseInt(id), idOfTbFactoryingOperator, mhtnofrom, pwd,CommonUtils.getInteger(idofLoanInfo),rowUpdateTime,tsOfLoanInfo,voucher,null,null);
         return new Result(Result.Status.OK,"放款成功");
     }catch (Exception e){
         if(e instanceof IPayNowException){
             return new Result(Result.Status.WARNING,"处理中");
         }
         log.error("放款失败",e);
         if(e instanceof BusinessException){
             return new Result(Result.Status.ERROR,e.getMessage());
         }
         return new Result(Result.Status.ERROR,"放款失败");
     }
    }
    //对账
    @ResponseBody
    @RequestMapping(value = "/slcheckaccount",method = RequestMethod.GET)
    public Result slcheckaccount(HttpServletRequest request ){
        Integer  userIdOfJoinOfCreditor=TradeUtils.getOperatorCompany(request);
        try{
            List<TbSlLoanCreditLogVo> list=tbSlLoanCreditService.queryAllNotPayBackCreditLog(userIdOfJoinOfCreditor);
            return new Result(Result.Status.OK,list);
        }catch(Exception e){
            log.error("对账失败",e);
            if(e instanceof  BusinessException){
                return new Result(Result.Status.ERROR,e.getMessage());
            }
            return new Result(Result.Status.ERROR,"对账失败");
        }

    }
    //下载用户的贷款申请书
    public void downloadSlLoanCommitFile(
            HttpServletRequest request,
            HttpServletResponse response,String id) {
        if(CommonUtils.isEmpty(id)){
            return;
        }
        TbSlLoanCreditLog creditlog= tbSlLoanCreditService.queryCreditLogById(Integer.parseInt(id));
        if(!CommonUtils.isEmpty(creditlog.getMaterial())){
            TbUploadFile uploadFileVO = uploadFileService.queryById(CommonUtils.getInt(creditlog.getMaterial()));
            String filename = "贷款编号"+creditlog.getCode()+IConstDef.DOWNLOAD_LOANAPPLY + "." + FilenameUtils.getExtension(uploadFileVO.getDownloadPath());
            try {
                DownloadUtils.download(request, response, FileUploadUtils.getDefaultBaseDir()+File.separator+uploadFileVO.getDownloadPath(), filename);
            }catch (Exception e) {
                LogUtils.info(log, "下载%s",IConstDef.DOWNLOAD_LOANAPPLY);
            }
        }
    }
    //下载贷款
    @ResponseBody
    @RequestMapping(value="/downloadSlLoanRenewedFile",method =RequestMethod.GET )
    public void downloadSlLoanRenewedFile(HttpServletRequest request,HttpServletResponse response,String id){
        if(CommonUtils.isEmpty(id)){
            return;
        }
        TbSlLoanCreditLog creditlog= tbSlLoanCreditService.queryCreditLogById(Integer.parseInt(id));
        if(!CommonUtils.isEmpty(creditlog.getRenewedUpload())){
            TbUploadFile uploadFileVO = uploadFileService.queryById(CommonUtils.getInt(creditlog.getRenewedUpload()));
            String filename = "贷款编号"+creditlog.getCode()+IConstDef.DOWNLOAD_RENEWEDAPPLY + "." + FilenameUtils.getExtension(uploadFileVO.getDownloadPath());
            try {
                DownloadUtils.download(request, response, FileUploadUtils.getDefaultBaseDir()+File.separator+uploadFileVO.getDownloadPath(), filename);
            }catch (Exception e) {
                LogUtils.info(log, "下载%s",IConstDef.DOWNLOAD_RENEWEDAPPLY);
            }
        }



    }
    @ResponseBody
    @RequestMapping(value = "/calculatefee",method = RequestMethod.GET)
    public Result calculateFee(HttpServletRequest request){
        try{
            tbSlLoanCaculateFeeService.updateCaculateFee();
            return new Result(Result.Status.OK,"计息成功");
        } catch (Exception e){
            LogUtils.error(log, e, "计息失败");
            return new Result(Result.Status.ERROR,"计息失败");
        }
    }

    @ResponseBody
    @RequestMapping(value = "/autorepay",method = RequestMethod.GET)
    public Result autoRepay(HttpServletRequest request){
        try{
            loanService.execAutomaticRepayLoan(ISLConstDef.MANU_OPERATOR);
            return new Result(Result.Status.OK,"自动还款成功");
        }catch (Exception e){
            LogUtils.error(log,e,"自动还款失败");
            return new Result(Result.Status.ERROR,"自动还款失败");
        }


    }
    
    @ResponseBody
    @RequestMapping(value = "/slQueryAndGenRepayTask",method = RequestMethod.GET)
    public Result slQueryAndGenRepayTask(HttpServletRequest request){
        try{
            loanService.queryFinanceInfo();
            return new Result(Result.Status.OK,"查询金融户余额并生成还款任务成功");
        }catch (Exception e){
            LogUtils.error(log,e,"查询金融户余额并生成还款任务失败");
            return new Result(Result.Status.ERROR,"查询金融户余额并生成还款任务失败");
        }
    }
    
    @ResponseBody
    @RequestMapping(value = "/checkaccount",method = RequestMethod.GET)
    public Result checkAccount(HttpServletRequest request,String curdate,Pageable page){
        try{
            List<TbSlCheckAccVo> list= tbSlLoanRefundService.queryCheckAccVo(curdate,page);
            return new Result(Result.Status.OK,list);
        }catch (Exception  e){
            LogUtils.error(log,e,"对账失败");
            return new Result(Result.Status.ERROR,"对账失败");
        }

    }

    @ResponseBody
    @RequestMapping(value="/queryplatdetail",method = RequestMethod.GET)
    public Result queryPlatDetail(HttpServletRequest request,String joinidstr){
        if(CommonUtils.isEmpty(joinidstr)){
            return new Result(Result.Status.ERROR,"查询的商户为空，请选择商户后再查询");
        }
        try{
            Integer joinid=Integer.parseInt(joinidstr);
            List<TbSlPlatformUserWithdrawVO> list=loanService.queryPlatformDetailForOperator(joinid);
            return new Result(Result.Status.OK,list);
        }catch (Exception e){
            LogUtils.error(log,e,"查询平台明细有误");
            if(e instanceof  BusinessException){
                return new Result(Result.Status.ERROR,e.getMessage());
            }
            return new Result(Result.Status.ERROR,"查询平台明细有误");
        }

    }
    @ResponseBody
    @RequestMapping(value="/queryplatdetailforfirsttrial",method = RequestMethod.GET)
    public Result queryPlatDetailByFirstTrial(HttpServletRequest request,String joinidstr){
        if(CommonUtils.isEmpty(joinidstr)){
            return new Result(Result.Status.ERROR,"查询的商户为空，请选择商户后再查询");
        }
        try{
            Integer joinid=Integer.parseInt(joinidstr);
            List<TbSlPlatformUserWithdrawVO> list=loanService.queryCanLoadByFirstTrail(joinid);
            return new Result(Result.Status.OK,list);
        }catch (Exception e){
            LogUtils.error(log,e,"查询平台明细有误");
            if(e instanceof  BusinessException){
                return new Result(Result.Status.ERROR,e.getMessage());
            }
            return new Result(Result.Status.ERROR,"查询平台明细有误");
        }

    }


    @ResponseBody
    @RequestMapping(value = "/preloan",method = RequestMethod.GET)
    public Result preLoan(HttpServletRequest request,String joinidstr,String amount){
       if(CommonUtils.isEmpty(joinidstr)){
           return new Result(Result.Status.ERROR,"待放款的商户为空");
       }
        if(CommonUtils.isEmpty(amount)){
            return new Result(Result.Status.ERROR,"请输入提款金额");
        }

        double amountdouble = Double.parseDouble(amount);
        if(amountdouble<10000){
            return new Result(Result.Status.ERROR,"融资最小额度为10000元");
        }
        BigDecimal decimal = new BigDecimal(amountdouble * 100).setScale(0, BigDecimal.ROUND_HALF_UP);
        long amountlong = decimal.longValue();
            int joinid=Integer.parseInt(joinidstr);
           String mthno=userBaseService.queryPayUserByJoinUserID(joinid);
                try{
            TbSlLoanCreditVoForFront voForFront = loanService.queryPreLoan(amountlong,joinid,mthno, ISLConstDef.OPERATOR_TYPE);
            return new Result(Result.Status.OK,voForFront);
        } catch (Exception e){
            LogUtils.error(log,e,"预提款失败");
            if(e instanceof BusinessException){
                return new Result(Result.Status.ERROR,e.getMessage());
            }
            return  new Result(Result.Status.ERROR,"系统异常");
        }



    }

    @ResponseBody
    @RequestMapping(value = "/slapplyloan", method = RequestMethod.POST)
    public Result slApplyLoan(HttpServletRequest request,@RequestBody SlApplyLoanParam param){
        if (CommonUtils.isEmpty(param.getAmount())) {
            return new Result(Result.Status.ERROR, "提款金额不能为空");
        }
        double amountdouble = Double.parseDouble(param.getAmount());
        BigDecimal decimal = new BigDecimal(amountdouble * 100).setScale(0, BigDecimal.ROUND_HALF_UP);
        long amountlong = decimal.longValue();
        if(amountlong<=0){
            return new Result(Result.Status.ERROR,"提款金额必须大于0");
        }

        int idOfTbFactoryingCompany=TradeUtils.getOperatorCompany(request);
        Integer idOfTbFactoryingOperator=CommonUtils.getLoginUserId();
        String mhtnofrom=TradeUtils.getOperatorCompanyMhtNo();
        try{
	        String joinstr=param.getJoinidstr();
	        if(CommonUtils.isEmpty(joinstr)){
	            return new Result(Result.Status.ERROR,"未获取到要放款商户的id");
        }

        int joinid=Integer.parseInt(joinstr);
        String mthno=userBaseService.queryPayUserByJoinUserID(joinid);
        loanService.updateForSlApplyLoan(amountlong,joinid,mthno,param.getFrontvo(),idOfTbFactoryingOperator,mhtnofrom,param.getVoucher(),idOfTbFactoryingCompany);
        return new Result(Result.Status.OK,"放款成功");

    }catch (Exception e){
        if(e instanceof  BusinessException){
            LogUtils.error(log,e,"放款失败");
           return  new Result(Result.Status.ERROR,e.getMessage());
        }
        return  new Result(Result.Status.ERROR,"放款失败");
    }


}
  @ResponseBody
  @RequestMapping(value = "/queryNotpayback",method = RequestMethod.GET)
  public Result queryNotpayback(HttpServletRequest request,String joinidstr){
    if(CommonUtils.isEmpty(joinidstr)){
        return new Result(Result.Status.ERROR,"未设置查询商户");
    }
      int joinid=Integer.parseInt(joinidstr);
    try{
        List<TbSlNotPayBackCredit> list= tbSlLoanCreditService.queryCreditNotPayBackForSl(joinid);
        return new Result(Result.Status.OK,list);

    }catch (Exception e){
        LogUtils.error(log,e,"查询该商户的贷款记录出错");
        if(e instanceof BusinessException){
            return  new Result(Result.Status.ERROR,e.getMessage());
        }
        return new Result(Result.Status.ERROR,"查询该商户的贷款记录出错");
    }


  }
    @ResponseBody
    @RequestMapping(value="/preRefund",method = RequestMethod.GET)
    public Result  preRefund(HttpServletRequest request,String amount,String joinidstr){
        if(CommonUtils.isEmpty(amount)){
            return new Result(Result.Status.ERROR,"输入的金额为空");
        }
        double amountdouble = Double.parseDouble(amount);
        BigDecimal decimal = new BigDecimal(amountdouble * 100).setScale(0, BigDecimal.ROUND_HALF_UP);
        long amountlong = decimal.longValue();
        if(amountlong<=0){
            return new Result(Result.Status.ERROR,"还款金额必须大于0");
        }
        try{
            if(CommonUtils.isEmpty(joinidstr)){
                return new Result(Result.Status.ERROR,"未获取到要还款商户的id");
            }
            int joinid=Integer.parseInt(joinidstr);
            long liabilitiesAmount= tbSlLoanInfoService.queryTotalNotPayback(joinid);
            if(liabilitiesAmount<amountlong){
                return new Result(Result.Status.ERROR,"还款金额大于欠款额");
            }
            String mthno=userBaseService.queryPayUserByJoinUserID(joinid);
            TbSlRefundForFrontVo vo =loanService.autoGenerationRefund(amountlong,joinid,mthno,"operator");
            return new Result(Result.Status.OK,vo);
        }catch (Exception e){
            LogUtils.error(log,e,"保理员后台还款失败");
            if(e instanceof  BusinessException){
                return new Result(Result.Status.ERROR,e.getMessage());
            }
            return new Result(Result.Status.ERROR,"系统异常");
        }
    }
    @ResponseBody
    @RequestMapping(value = "/autoRefund",method = RequestMethod.POST)
    public Result autoRefund(HttpServletRequest request,@RequestBody SlRapayParam param){

        if(CommonUtils.isEmpty(param.getAmount())){
            return new Result(Result.Status.ERROR,"请输入还款金额");
        }
        double amountdouble = Double.parseDouble(param.getAmount());
        BigDecimal decimal = new BigDecimal(amountdouble * 100).setScale(0, BigDecimal.ROUND_HALF_UP);
        long amountlong = decimal.longValue();
        if(amountlong<=0){
            return new Result(Result.Status.ERROR,"还款金额必须大于0元");
        }
        try{
            if(CommonUtils.isEmpty(param.getJoinidstr())){
                return new Result(Result.Status.ERROR,"未获取到要还款商户的id");
            }
            int joinid=Integer.parseInt(param.getJoinidstr());
            String mthno=userBaseService.queryPayUserByJoinUserID(joinid);
            long liabilitiesAmount= tbSlLoanInfoService.queryTotalNotPayback(joinid);
            if(liabilitiesAmount<amountlong){
                return new Result(Result.Status.ERROR,"还款金额大于欠款额");
            }

            loanService.updateForAutoRepayForOperator(amountlong,joinid,mthno,param.getVoucher(),param.getVo());
            return new Result(Result.Status.OK,"还款成功");
        }catch (Exception e){
            if(e instanceof  BusinessException){
                return new Result(Result.Status.ERROR,e.getMessage());
            }
            return new Result(Result.Status.ERROR,"还款失败");
        }
    }
    @ResponseBody
    @RequestMapping(value="/queryplatformdetail",method = RequestMethod.GET)
    public Result queryPlatformDetail(HttpServletRequest request,String joinid){
       if(CommonUtils.isEmpty(joinid)){
           return new Result(Result.Status.ERROR,"未选择任何商户");
       }
        try{

            List<TbSlPlatformUserWithdrawVO> list=loanService.queryPlatformDetail(Integer.parseInt(joinid));
            return new Result(Result.Status.OK,list);
        }catch (Exception e){
            LogUtils.error(log,e,"查询平台明细有误");
            if(e instanceof  BusinessException){
                return new Result(Result.Status.ERROR,e.getMessage());
            }
            return new Result(Result.Status.ERROR,"查询平台明细有误");
        }
    }
    @ResponseBody
    @RequestMapping(value = "/queryRefund",method = RequestMethod.GET)
    public Result queryRefund(HttpServletRequest request,Pageable page,String joinid){
        if(CommonUtils.isEmpty(joinid)){
            return new Result(Result.Status.ERROR,"查询商户为空");
        }
        try{
            List<TbSlLoanRefundVo> list= tbSlLoanRefundService.queryLoanRefundlist(Integer.parseInt(joinid),page);
            return new Result(Result.Status.OK,list);
        }catch (Exception e){
            LogUtils.error(log,e,"查询用户的贷款数据出错");
        }
        return new Result(Result.Status.ERROR,"查询用户的贷款数据出错");
    }
    @ResponseBody
    @RequestMapping(value="/queryLoanInfo",method = RequestMethod.GET)
    public Result queryLoanInfo(HttpServletRequest request,Pageable page){
        try{
            List<TbSlLoanInfoVo>  list=tbSlLoanInfoService.queryAllTbSlLoanInfo();
            return new Result(Result.Status.OK,list);
        }catch (Exception e){
            LogUtils.error(log,e,"查询所有商户的实时账户信息出错");
        }
              return  new Result(Result.Status.ERROR,"查询商户的实时账户信息出错");
    }
    @ResponseBody
    @RequestMapping(value="/queryFinaceaccount",method = RequestMethod.GET)
    public Result queryFinaceaccount(HttpServletRequest request,String joinid){
        if(CommonUtils.isEmpty(joinid)){
            return new Result(Result.Status.ERROR,"");
        }
        try{
       Integer id_of_merchant=Integer.parseInt(joinid);
        List<TbMerchantuserFinaccount> list=tbMerchantuserFinaccountService.queryFinaccountByJoinid(id_of_merchant,IConstDef.TYPE_SUPPLYLOAN);
       return new Result(Result.Status.OK,list);
        }catch (Exception e){
          LogUtils.error(log,e,"根据商户查询金融户报错");
            return new Result(Result.Status.ERROR,"根据商户查询金融户报错"+joinid);
        }

    }
    @ResponseBody
    @RequestMapping(value="/addFinaceaccount",method = RequestMethod.POST)
    public Result addFinaceaccount(HttpServletRequest request,@RequestBody TbMerchantuserFinaccount account){
        if(CommonUtils.isEmpty(account)){
            return new Result(Result.Status.ERROR,"新增的账户报错");
        }
        try{
            String acctype=account.getAccountType();
            if(CommonUtils.isEmpty(acctype)){
                return new Result(Result.Status.ERROR,"账户类型不能为空");
            }
            Integer joinid=account.getIdOfTbMerchantUser();
            if(CommonUtils.isEmpty(joinid)){
                return new Result(Result.Status.ERROR,"商户不能为空");
            }
            Integer business_type=account.getBusinessType();
            if(CommonUtils.isEmpty(business_type)) {
                return new Result(Result.Status.ERROR,"业务类型不能为空");
            }
            
            tbMerchantuserFinaccountService.insertTbMerchantuserFinaccount(account);
            return new Result(Result.Status.OK,"操作成功");
        }catch (Exception e){
            LogUtils.error(log,e,"新增金融户报错");
           return new Result(Result.Status.ERROR,"操作失败");
        }
    }
    @ResponseBody
    @RequestMapping(value = "/queryRenewedCredit",method = RequestMethod.GET)
    public Result queryRenewedCredit(HttpServletRequest request,Pageable page,Integer userIdOfJoinOfDebtor,Integer idOfPlatform,String begintime,String endtime){
        Integer  userIdOfJoinOfCreditor=TradeUtils.getOperatorCompany(request);
        try{
            List<TbSlStatusCreditLogVo> list=tbSlLoanCreditService.queryRenewedCredit(userIdOfJoinOfCreditor,userIdOfJoinOfDebtor,idOfPlatform,begintime,endtime,page);
            return new Result(Result.Status.OK,list);
        }catch (Exception e){
            LogUtils.error(log,e,"查询需要展期的贷款数据出错");
            return new Result(Result.Status.ERROR,"查询需要展期的贷款数据出错");
        }

    }

    @ResponseBody
    @RequestMapping(value = "/agreeRenewed",method = RequestMethod.POST)
    public Result agreeRenewed(HttpServletRequest request,@RequestBody SlCreditRenewedVo vo){
        if(CommonUtils.isEmpty(vo)){
            return new Result(Result.Status.ERROR,"传入参数为空");
        }
        if(CommonUtils.isEmpty(vo.getRenewedRate())){
            return new Result(Result.Status.ERROR,"展期日利率为空");
        }
        if(CommonUtils.isEmpty(vo.getRenewedfee())){
            return new Result(Result.Status.ERROR,"展期手续费率为空");
        }
         if(CommonUtils.isEmpty(vo.getRenewedBegintime())){
             return new Result(Result.Status.ERROR,"展期起始时间不能为空");
         }
        if(CommonUtils.isEmpty(vo.getRenewedEndTime())){
            return new Result(Result.Status.ERROR,"展期的结束时间不能为空");
        }
        if(CommonUtils.isEmpty(vo.getId())){
             return new Result(Result.Status.ERROR,"贷款id为空");
        }
        if(CommonUtils.isEmpty(vo.getRenewedAmount())){
            return new Result(Result.Status.ERROR,"展期服务费不能为空");
        }
        try{
              loanService.updateForAgreeRenewed(vo);
            return new Result(Result.Status.OK,"展期审批成功");
        }catch (Exception e){
            if(e instanceof BusinessException){
                return new Result(Result.Status.ERROR,e.getMessage());
            }
            return new Result(Result.Status.ERROR,"通过展期失败");
        }

    }
    @ResponseBody
    @RequestMapping(value = "/refuseRenewed",method = RequestMethod.POST)
    public Result refuseRenewed(HttpServletRequest request,Integer id,String rowUpdateTime,String memo) {
        if(CommonUtils.isEmpty(id)){
            return new Result(Result.Status.ERROR,"贷款id为空");
        }
        if(CommonUtils.isEmpty(rowUpdateTime)){
            return new Result(Result.Status.ERROR,"时间戳不能为空");
        }
        if(CommonUtils.isEmpty(memo)){
            return new Result(Result.Status.ERROR,"拒绝原因不能为空");
        }
 
           try {
               loanService.updateRefuseRenewed(id,rowUpdateTime,memo);
               return new Result(Result.Status.OK,"展期拒绝成功");
                }catch (Exception e){
               if(e instanceof BusinessException){
                    return new Result(Result.Status.ERROR,e.getMessage());
               }
               return new Result(Result.Status.ERROR,"展期拒绝失败");

           }
    }
    @ResponseBody
    @RequestMapping(value = "/queryFloat",method = RequestMethod.GET)
    public Result queryFloat(HttpServletRequest request,Integer userIdOfJoinOfDebtor,Integer idOfPlatform,String code,Pageable page){
        Map<String,Object> param=new HashMap<>();
        if(!CommonUtils.isEmpty(userIdOfJoinOfDebtor)){
            param.put("userIdOfJoinOfDebtor",userIdOfJoinOfDebtor);
        }
        if(!CommonUtils.isEmpty(idOfPlatform)){
            param.put("idOfPlatform",idOfPlatform);
        }
        if(!CommonUtils.isEmpty(code)){
            param.put("code",code);
        }
        try{
            Integer  userIdOfJoinOfCreditor=TradeUtils.getOperatorCompany(request);
            param.put("userIdOfJoinOfCreditor",userIdOfJoinOfCreditor);
            param.put("curdate", TimeUtils.getCurDate());
            List<TbSlLoanCreditLogVo> list=tbSlLoanCreditService.queryCreditForFloat(param,page);
            return new Result(Result.Status.OK,list);
        }catch (Exception e){
            LogUtils.error(log,e,"查询贷款情况出错");
            if(e instanceof BusinessException){
                return new Result(Result.Status.ERROR,e.getMessage());
            }
            return new Result(Result.Status.ERROR,"查询贷款情况出错");
        }
    }

    @ResponseBody
    @RequestMapping(value="/addFloatVo",method = RequestMethod.POST)
    public Result addFloatVo(HttpServletRequest request,@RequestBody TbSlCreditForFloatVo vo){
        Integer operator=CommonUtils.getLoginUserId();
         List<TbSlLoanFloat> list=vo.getList();
        if(CommonUtils.isEmpty(list)){
            return new Result(Result.Status.ERROR,"调息信息不能为空");
        }
        for(TbSlLoanFloat floatvo:list){
            floatvo.setIdOfOperator(operator);
        }
        Integer id=vo.getId();
        Date tsofcredit=vo.getRowUpdateTime();
        Integer idofloaninfo=vo.getIdOfLoanInfo();
        Date tsloaninfo=vo.getLoanInfoTs();
        if(CommonUtils.isEmpty(id)){
            return new Result(Result.Status.ERROR,"贷款信息不能为空");
        }
        if(CommonUtils.isEmpty(tsofcredit)){
            return new Result(Result.Status.ERROR,"贷款ts不能为空");
        }
        if(CommonUtils.isEmpty(idofloaninfo)){
            return new Result(Result.Status.ERROR,"贷款信息表不能为空");
        }
        if(CommonUtils.isEmpty(tsloaninfo)){
            return new Result(Result.Status.ERROR,"贷款信息总表的ts不能为空");
        }
       try{
           loanService.updateLoanFloat(vo);
           return new Result(Result.Status.OK,"新增调息信息成功");
           }catch (Exception e){
           LogUtils.error(log,e,"新增调息情况失败");
           if(e instanceof BusinessException){
              return new Result(Result.Status.ERROR,e.getMessage());
           }
           return new Result(Result.Status.ERROR,"新增调息信息有误");
       }

    }
    @ResponseBody
    @RequestMapping(value="/queryReNewedByID",method = RequestMethod.GET)
    public Result queryReNewedByID(HttpServletRequest request,Integer idOfcredit)
    {
       try
       {
           TbSlLoanCreditLog log=tbSlLoanCreditService.queryCreditLogById(idOfcredit);
           SlCreditRenewedVo vo=new SlCreditRenewedVo();
           vo.setRenewedAmount(log.getTotalNotPaybackRenewedAmount());
           vo.setRenewedRate(log.getRenewedRate());
           vo.setRenewedfee(log.getRenewedFee());
           vo.setRenewedBegintime(log.getRenewedBeginTime());
           vo.setRenewedEndTime(log.getRenewedRefundTime());
           vo.setAmount(log.getTotalNotPaybackAmount());
           vo.setId(log.getId());
           return new Result(Result.Status.OK,vo);
       }catch (Exception e){
           LogUtils.error(log,e,"查询贷款的展期信息失败");
           if(e instanceof BusinessException){
               return new Result(Result.Status.ERROR,e.getMessage());
           }
           return new Result(Result.Status.ERROR,"查询贷款的展期信息失败");
       }


    }
    @ResponseBody
    @RequestMapping(value="/queryCredit",method = RequestMethod.GET)
    public Result queryCredit(HttpServletRequest request,Integer id){
      try{
          TbSlStatusCreditLogVo vo=tbSlLoanCreditService.queryInfoById(id);
          return new Result(Result.Status.OK,vo);
      }catch (Exception e){
          LogUtils.error(log,e,"查询贷款数据出错");
         return new Result(Result.Status.ERROR,"查询报错");
      }


    }
    @ResponseBody
    @RequestMapping(value="/queryCreditForCheck",method = RequestMethod.GET)
    public Result queryCreditForCheck(HttpServletRequest request,Integer processinfoid){
    try{
          List<TbSlStatusCreditLogVo> list=tbSlLoanCreditService.queryCreditByProcessid(processinfoid);
         return new Result(Result.Status.OK,list);
    }catch (Exception e){
        if(e instanceof BusinessException){
            return new Result(Result.Status.ERROR,e.getMessage());
        }
        return new Result(Result.Status.ERROR,"查询贷款数据失败");
    }

    }
    @ResponseBody
    @RequestMapping(value="/queryRedo",method = RequestMethod.GET)
   public Result queryRedo(HttpServletRequest request){
           try{
               List<TbRedo> list=tbRedoService.queryAll();
               return new Result(Result.Status.OK,list);
           }catch (Exception e){
               LogUtils.error(log,e,"查询需要重新做的失败");
               return new Result(Result.Status.ERROR,"查询失败");
                 }
    }

    @ResponseBody
    @RequestMapping(value="/redo",method = RequestMethod.GET)
    public Result redo(HttpServletRequest request,String orderid){
      if(CommonUtils.isEmpty(orderid)){
          return new Result(Result.Status.ERROR,"转账id不能为空");
      }
        try{
        TbRedo vo=tbRedoService.queryTbReDoByBusinessId(orderid);
        Map map=(Map)CommonUtils.unserialize(vo.getParamstr());
        if(IConstDef.REPAY.equals(vo.getBusinessType())){
         Long amount=(Long)map.get("amount");
         Integer joinid=(Integer)map.get("joinid");
         TbSlRefundForFrontVo refundvo=(TbSlRefundForFrontVo)map.get("vo");
         loanService.updateForRedoAutoRepayLoanByJoinid(amount,joinid,refundvo,orderid,vo.getApplyDate());
        }else if(IConstDef.REPAYBYSELF.equals(vo.getBusinessType())){
            Integer joinid=(Integer)map.get("joinid");
            List<TbSlNotPayBackCredit> listvo=(List<TbSlNotPayBackCredit>)map.get("listvo");
            TbSlLoanInfo loaninfovo=(TbSlLoanInfo)map.get("loaninfovo");
            String accamount=(String)map.get("accamount");
            String applydate=vo.getApplyDate();
            String repayAcccountType=(String)map.get("repayAcccountType");
           loanService.updateForReDoRepayLoan(joinid,listvo,loaninfovo,accamount,applydate,repayAcccountType,orderid);
        }else if(IConstDef.AUTOREPAY.equals(vo.getBusinessType())){
          Long amount=(Long)map.get("amount");
          Integer joindid=(Integer)map.get("joinid");
          String applydate=vo.getApplyDate();
           loanService.updateForRedoRepayLoanByJoinid(amount,joindid,applydate,orderid);
        }else if(IConstDef.LOAN.equals(vo.getBusinessType())){
         Integer processInfoId=(Integer)map.get("processInfoId");
         Integer idOfTbFactoryingOperator=(Integer)map.get("idOfTbFactoryingOperator");
         String mhtnofrom=(String)map.get("mhtnofrom");
         Integer idofLoanInfo=(Integer)map.get("idofLoanInfo");
            String ts=(String)map.get("ts");
          String tsOfLoanInfo=(String)map.get("tsOfLoanInfo");
         String voucher=(String)map.get("voucher");
         String taskid=(String)map.get("taskid");
            String processid=(String)map.get("processid");
          loanService.updateForRedoRealLoan(processInfoId, idOfTbFactoryingOperator, mhtnofrom, idofLoanInfo, ts, tsOfLoanInfo, voucher, vo.getApplyDate(), orderid,taskid,processid);
        }
        //T1还款及放款操作
        else if (IConstDef.T0_LOAN_RETURN.equals(vo.getBusinessType()) ||
	        		IConstDef.T1_LOAN_RETURN.equals(vo.getBusinessType()) || 
	        		IConstDef.D1_LOAN_RETURN.equals(vo.getBusinessType())) {
        	TbT0RefundTaskVO refundtaskvo = (TbT0RefundTaskVO) map.get("refundtaskvo");
        	t0loanService.updateRunEachRefundRedoTask(refundtaskvo, orderid);
        } else if (IConstDef.T0_LOAN_CREDIT.equals(vo.getBusinessType()) ||
	        		IConstDef.T1_LOAN_CREDIT.equals(vo.getBusinessType()) || 
	        		IConstDef.D1_LOAN_CREDIT.equals(vo.getBusinessType())) {
            String loanlogid = (String) map.get("loanlogid");
            String operatetype = (String) map.get("operatetype");
            String paypwd = (String) map.get("paypwd");
            t0loanService.updateCreditLoanRedo(CommonUtils.getInt(loanlogid), operatetype, paypwd, orderid);
        } else if (IConstDef.TX_LOAN_DRAW.equals(vo.getBusinessType())) {
        	 String loanlogid = (String) map.get("loanlogid");
             String pagets = (String) map.get("pagets");
             translogService.drawByTransLogRefundRedo(CommonUtils.getInt(loanlogid), pagets, orderid);
        }
            return new Result(Result.Status.OK,"重新处理成功");
        }catch (Exception e){
            LogUtils.error(log,e);
            if(e instanceof BusinessException){
                return new Result(Result.Status.ERROR,e.getMessage());
            }
            else
                return new Result(Result.Status.ERROR,"重新处理失败");
        }




    }
    @ResponseBody
    @RequestMapping(value="/sendmsg",method = RequestMethod.POST)
    public Result sendmsg(HttpServletRequest request,String orderid,String msg){

        try{
            loanService.updateForDealRedoWithFailure(orderid,msg);
            return new Result(Result.Status.OK,"处理成功");
        }catch (Exception e){
            LogUtils.error(log,e,"处理失败");
            return new Result(Result.Status.ERROR,"处理失败");
        }



    }
    @ResponseBody
    @RequestMapping(value="/querywillexpire",method = RequestMethod.GET)
    public Result querywillexpire(HttpServletRequest request,Pageable pageable){

        try{
            List<TbSlLoanCreditLogVo> list= tbSlLoanCreditService.queryWillExpireCreditForOperator(pageable);
            return new Result(Result.Status.OK,list);
        }catch (Exception e){
            LogUtils.error(log,e,"查询即将过期的贷款数据失败");
            if(e instanceof BusinessException){
                return new Result(Result.Status.ERROR,e.getMessage());

            }
            else{
                 return new Result(Result.Status.ERROR,"查询即将过期的贷款数据失败");
            }
        }
    }
    
    @ResponseBody
    @RequestMapping(value="/queryLoanbill",method = RequestMethod.GET)
    public Result queryLoanbill(HttpServletRequest request,Pageable pageable,String begintime,String endtime,Integer userIdOfJoinOfDebtor)
    {
        try{
            int joinid=TradeUtils.getOperatorCompany(request);
            List<SLLoanBillBaseInfoVo> list= tbSlLoanCreditService.querySlloanBillVo(begintime,endtime,userIdOfJoinOfDebtor,joinid,pageable);
            return new Result(Result.Status.OK,list);
        }catch (Exception e){
            LogUtils.error(log,e,"查询融资的对账信息出错");
           return new Result(Result.Status.ERROR,"查询融资的对账信息出错");
        }
    }
    
    @ResponseBody
    @RequestMapping(value="/queryRefundBill",method = RequestMethod.GET)
    public Result queryRefundBill(HttpServletRequest request,Pageable pageable,String begintime,String endtime,Integer userIdOfJoinOfDebtor)
    {
        try{
            int joinid=TradeUtils.getOperatorCompany(request);
            List<SLRefundBaseInfoVo> list=tbSlLoanRefundService.queryRefundBillVo(begintime, endtime, userIdOfJoinOfDebtor,joinid, pageable);
            return new Result(Result.Status.OK,list);
        }catch (Exception e){
            LogUtils.error(log,e,"查询还款对账信息出错");
            return new Result(Result.Status.ERROR,"查询还款对账信息出错");
        }
    }
    
    @ResponseBody
    @RequestMapping(value = "/queryDailyLoanInfo",method = RequestMethod.GET)
    public Result queryDailyLoanInfo(HttpServletRequest request,Pageable pageable,String curdate,Integer idOfTbMerchantUser)
    {
       try{
           int joinid=TradeUtils.getOperatorCompany(request);
           List<TbSlLoanDailyBillVo> loanDailyBillVos=tbSlLoanInfoService.queryDailyBill(curdate,idOfTbMerchantUser,joinid,pageable);
           return new Result(Result.Status.OK,loanDailyBillVos);
       }catch (Exception e){
           LogUtils.error(log,e,"查询对账日报表出错");
             return new Result(Result.Status.ERROR,"查询对账日报表出错");
       }
    }
    
    @ResponseBody
    @RequestMapping(value = "/queryLoanSum",method = RequestMethod.GET)
    public Result  queryLoanSum(HttpServletRequest request,String begintime,String endtime,Integer userIdOfJoinOfDebtor){
        try{
            int joinid=TradeUtils.getOperatorCompany(request);
            SLLoanBillVo vo=tbSlLoanCreditService.querySlLoanBillSumvo(begintime, endtime, userIdOfJoinOfDebtor, joinid);
            return new Result(Result.Status.OK,vo);
        }catch (Exception e){
            LogUtils.error(log,e,"查询欠款额出错");
            return new Result(Result.Status.ERROR,"查询总的贷款额和未还贷款额出错");
        }
    }
    
    @ResponseBody
    @RequestMapping(value="/queryRefundSum",method = RequestMethod.GET)
    public Result queryRefundSum(HttpServletRequest request,String begintime,String endtime,Integer userIdOfJoinOfDebtor){

        try{
            int joinid=TradeUtils.getOperatorCompany(request);
            SLRefundBillVo vo=tbSlLoanRefundService.querySlRefundBillSumvo(begintime, endtime, userIdOfJoinOfDebtor, joinid);
            return new Result(Result.Status.OK,vo);
        }catch (Exception e){
            LogUtils.error(log,e,"查询已还贷款本金和利息出错");
            return new Result(Result.Status.ERROR,"查询已还贷款本金和利息出错");
        }
    }
    
    @ResponseBody
    @RequestMapping(value ="/queryDailySum",method = RequestMethod.GET)
    public Result   queryDailySum(HttpServletRequest request,String curdate,Integer idOfTbMerchantUser){
        try{
            int joinid=TradeUtils.getOperatorCompany(request);
             String  sum=tbSlLoanInfoService.queryDailySum(curdate,idOfTbMerchantUser,joinid);
            return new Result(Result.Status.OK,sum);
        }catch (Exception e){
            LogUtils.error(log,e,"查询对账总额出错");
            return new Result(Result.Status.ERROR,"查询对账日报总额出错");
        }
    }
    
    @RequestMapping(value = "/downloadSLDailyLoanFile", method = RequestMethod.GET)
	public void downloadSLDailyLoanFile(HttpServletRequest request, HttpServletResponse response, String curdate, Integer idOfTbMerchantUser) throws IOException {
    	ByteArrayOutputStream bos = new ByteArrayOutputStream();
    	
    	int joinid=TradeUtils.getOperatorCompany(request);
    	loanService.exportSLDailyLoanFile(curdate, idOfTbMerchantUser, joinid, bos);
    	String filename = "融资日报.xls";
    	DownloadUtils.download(request, response, filename, bos.toByteArray());
		LogUtils.info(log, "下载%s",IConstDef.DOWNLOAD_SLDAILYLOAN);
	}
    
    
}